package com.ton.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ton.domain.BookBean;
import com.ton.service.BookService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
 * 表现层方法
 * @author
 */
@RestController
@RequestMapping("/bookBeans")
public class BookController {

    @Resource
    private BookService bookService;
    //增
    @PostMapping
    public Result save(@RequestBody BookBean bookBean) {
        System.out.println(bookBean);
        boolean flag = bookService.save(bookBean);
        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag);
    }
    //删
    @PostMapping("/del")
    public Result delete(@RequestBody List<BookBean> data) {

       boolean flag =  bookService.deleteList(data);

        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR, flag);
    }
    //改
    @PutMapping
    public Result update(@RequestBody BookBean bookBean) {
        boolean flag = bookService.update(bookBean);
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag);
    }
    //查
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        BookBean bookBean = bookService.getById(id);
        Integer code = bookBean != null ? Code.GET_OK : Code.GET_ERR;
        String msg = bookBean != null ? "" : "数据查询失败，请重试！";
        return new Result(code, bookBean, msg);
    }
    //查
    @GetMapping
    public Result selectAll() {
        List<BookBean> bookBeans = bookService.selectAll();
        Integer code = bookBeans != null ? Code.GET_OK : Code.GET_ERR;
        String msg = bookBeans != null ? "" : "数据查询失败，请重试！";
        return new Result(code, bookBeans, msg);
    }
    //分页
    @GetMapping("/{currentPage}/{pageSize}")
    public Result getSinglePage(@PathVariable Integer currentPage, @PathVariable Integer pageSize, BookBean bookBean) {
        IPage<BookBean> page = bookService.getPage(currentPage, pageSize, bookBean);
        //如果当前页码值大于总页码值，重新查询
        if (currentPage > page.getPages()) {
            page = bookService.getPage((int) page.getPages(), pageSize, bookBean);
        }
        List<BookBean> bookBeans = page.getRecords();
        Integer code = bookBeans != null ? Code.GET_OK : Code.GET_ERR;
        String msg = bookBeans != null ? "" : "数据查询失败，请重试！";
        return new Result(code, page, msg);
    }

}
